package com.example.fast.web.controller.candidate;

import com.example.fast.common.annotation.Login;
import com.example.fast.common.annotation.LoginUser;
import com.example.fast.common.exception.BaseException;
import com.example.fast.common.util.R;
import com.example.fast.domain.entity.UserEntity;
import com.example.fast.domain.enums.UserTypeEnum;
import com.example.fast.domain.vo.LoginVo;
import com.example.fast.domain.vo.UserQuery;
import com.example.fast.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

import static com.example.fast.common.exception.AppExceptionEnum.USERNAME_OR_PASSWORD_ERROR;

/**
 * 应聘人接口
 */
@RestController("candidateUserController")
@RequestMapping("/v1/candidate/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public R<LoginVo> login(@RequestBody UserQuery userQuery) {
        userQuery.setUserType(UserTypeEnum.APPLICANT);
        Optional<LoginVo> optional = userService.login(userQuery);
        if (optional.isPresent()) {
            return R.ok(optional.get());
        }
        throw new BaseException(USERNAME_OR_PASSWORD_ERROR, "用户名或密码错误");
    }

    /**
     * 用户注册
     */
    @PostMapping("/reg")
    public R reg(@RequestBody UserQuery userQuery) {
        userQuery.setUserType(UserTypeEnum.APPLICANT);
        userService.reg(userQuery);
        return R.ok();
    }

    /**
     * 用户退出登录
     */
    @Login
    @PostMapping("/logout")
    public R logout() {
        return R.ok();
    }

    /**
     * 获取个人信息
     */
    @Login
    @GetMapping
    public R info(@LoginUser UserEntity user) {
        return R.ok(user);
    }

    /**
     * 更新个人信息
     */
    @Login
    @PutMapping
    public R updateUserInfo(@LoginUser UserEntity user, @RequestBody UserQuery userQuery) {
        userQuery.setUserId(user.getId());
        userService.updateUserInfo(userQuery);
        return R.ok();
    }
}
